import JSZip from 'jszip';
import { saveAs } from 'file-saver';


function downfile(url) {
  return new Promise((resolve, reject)=>{
    let xhr = new XMLHttpRequest();
    xhr.open('GET', url, true);
    xhr.responseType = 'blob';
    xhr.onload = function () {
      if (xhr.status === 200) {
        let fileblob = xhr.response;
        resolve(fileblob);
      }
    };
    xhr.send();
  })
}

export const renameFile = (filename,url)=>{
  saveAs(url,filename);
}

//表单序列化
export const zipdown = (zipname,files) => {
  if(files==null){
    return;
  }
  if(!Array.isArray(files)){
    files = [files];
  }


  let zip = JSZip()
  for (let i = 0; i < files.length; i++) {
    if(files[i].url){
      zip.file(files[i].name, downfile(files[i].url));
    }else  if(files[i].content){
      zip.file(files[i].name, files[i].content);
    }
  }

  zip.generateAsync({type:"blob"})
    .then(function (content) {
      // see FileSaver.js
      saveAs(content, zipname);
    });
};
